import { message } from 'antd'
import { forwardRef, useImperativeHandle } from 'react'
import services from '@/services'
import type { ExternalRelation } from '@/services/contact-types'
import { splitContactId } from '@/services/contacts'
import { empty, spin } from '.'
import './relation.module.less'

interface Props {
  contactId: string
}
export interface Ref {
  refresh: () => void
}

export default forwardRef<Ref, Props>(function Relation(props, ref) {
  const { contactId } = props
  const [ownerWxid, contactUserId] = splitContactId(contactId)

  const [relation, setRelation] = useState<ExternalRelation | null>(null)

  //const load = useCallback(async () => {
  //  const res = await services.externals.getRelation({ ownerWxid, contactUserId })
  //  if (res.success) setRelation(res.data)
  //  else void message.error(`获取客户资料失败：${res.error}`)
  //}, [ownerWxid, contactUserId])
  //useEffect(() => void load(), [load])

  const refresh = useCallback(async () => {
    setRelation(null)
    const res = await services.externals.refreshRelation(contactId)
    if (res.success) setRelation(res.data)
    else void message.error(`刷新客户资料失败：${res.error}`)
  }, [contactId])

  useImperativeHandle(ref, () => ({ refresh }))

  // ===================================

//  const copyContent = `wxid: ${contactUserId}
//ExternalUserId: ${relation?.externalUserId ?? ''}
//UnionId: ${relation?.unionId ?? ''}`
//  const copyRef = useRef<HTMLTextAreaElement>(null)
//  const copyRelation = useCallback(() => {
//    if (!relation || !copyRef.current) return
//    copyRef.current.select()
//    document.execCommand('copy')
//    copyRef.current.blur()
//  }, [relation, copyRef])

  return <section styleName="relation">
    <div className="row">
      <label>UserId</label>
      <div>{contactUserId}</div>
    </div>
    {/*<div className="row">*/}
    {/*  <label>ExternalUserId</label>*/}
    {/*  <div>{relation ? relation.externalUserId || empty : spin}</div>*/}
    {/*</div>*/}
    {/*<div className="row">*/}
    {/*  <label>UnionID</label>*/}
    {/*  <div>{relation ? relation.unionId || empty : spin}</div>*/}
    {/*</div>*/}
    {/*<div className="row">*/}
    {/*  <label>添加时间</label>*/}
    {/*  <div>{relation ? relation.added || empty : spin}</div>*/}
    {/*</div>*/}
    {/*<div className="row">*/}
    {/*  <label>来源（add_way）</label>*/}
    {/*  <div>{relation ? (relation.addWayDescribe ?? '') || empty : spin}</div>*/}
    {/*</div>*/}
    {/*<div className="row">*/}
    {/*  <label>渠道标识（state）</label>*/}
    {/*  <div>{relation ? (relation.state ?? '') || empty : spin}</div>*/}
    {/*</div>*/}
    {/*<div className="row" styleName="actions">*/}
    {/*  <div>*/}
    {/*    <textarea ref={copyRef} key={copyContent} defaultValue={copyContent} />*/}
    {/*    <a onClick={copyRelation}>复制</a>*/}
    {/*  </div>*/}
    {/*</div>*/}
  </section>
})
